package com.example.demowithdb.controller;

import com.example.demowithdb.entity.book;
import com.example.demowithdb.mapper.bookMapper;
import com.example.demowithdb.exception.NotFoundException;
import com.example.demowithdb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Tag(name = "BookController", description = "利用HTTP状态码表示操作结果状态的控制器")
@RequestMapping("/api/books")
public class bookController {
    @Resource
    bookMapper BookMap;

    @Autowired
    private UserService userService; // Spring 注入 UserService

    @Operation(summary = "获取booklist", description = "返回值为全部的booklist")
    @GetMapping(path = "/", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public List<book> list(Model model) {
        List<book> books = BookMap.selectList(null);
        return books;
    }

    @Operation(summary = "根据id获取相应的book", description = "如果不存在，返回状态码为404")
    @GetMapping(path = "/{id}", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public book getById(@PathVariable("id") Long id) {
        book b = BookMap.selectById(id);
        if (b == null) {
            throw new NotFoundException();
        }
        return b;
    }

    @Operation(summary = "添加新的book", description = "创建成功，返回状态码201")
    @PostMapping(path = "/", consumes = "application/json", produces = "application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public book create(@RequestBody book b) {
        BookMap.insert(b);
        return b;
    }

    @Operation(summary = "根据id删除book")
    @DeleteMapping(path = "/{id}")
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable Long id) {
        if(BookMap.deleteById(id) <=0){
            throw new NotFoundException();
        }
        return;
    }

    @Operation(summary = "更新book", description = "如果不存在，则返回状态码404")
    @ResponseStatus(HttpStatus.OK)
    @PutMapping(path = "/{id}", consumes = "application/json", produces = "application/json")
    public book update(@PathVariable Long id, @RequestBody book b) {
        b.setId(id);
        if (BookMap.updateById(b) <= 0) {
            throw new NotFoundException();
        }
        return b;
    }
}
//
//    @PostMapping("/edit")
//    String edit(Model model,  @ModelAttribute book b, @RequestParam("img") MultipartFile file) {
//        if (userService.savePic(b, file)){
//            BookMap.update(b, null);
//            return "success"; //返回名为"success"的视图，即templates中的success.html
//        }
//        return "failure";
//    }
//}
